package com.project.controller.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.project.entity.InternInfo;
import com.project.entity.StudentInfo;
import com.project.entity.User;
import com.project.myBeans.InternInfoDetail;
import com.project.myBeans.ResponseBean;
import com.project.myBeans.StudentInfoDetail;
import com.project.service.*;
import com.project.service.base.BaseService;
import com.project.utils.Constants;
import com.project.utils.Constants.STUDENTSTATE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import static com.project.controller.web.StudentController.*;

/**
 * Created by WheelChen on 2017/5/15.
 * <p>
 * 实习信息相关操作
 */
@Controller
@RequestMapping(value = "/internInfo")
public class InternInfoController extends BaseService {
    @Autowired
    private UserService userService;

    @Autowired
    InternInfoService internInfoService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private ImagesService imagesService;

    /**
     * author: WheelChen
     * date: 2017-5-15
     * function: 模糊搜索分页显示
     *
     * @param internInfo
     * @return
     */
    @RequestMapping(value = "/findByCondition", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean findByCondition(@RequestBody InternInfo internInfo) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (internInfo.getPageIndex() > 0) // 若需要分页
                internInfo.setPageIndex(internInfo.getPageIndex() - 1);
            List<InternInfo> internInfos = internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails = new ArrayList<>();
            for (InternInfo internInfo1 : internInfos) {
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            responseBean.setData(internInfoDetails);
            responseBean.setTotal(internInfo.getTotal());
            responseBean.setSuccess(true);
            responseBean.setMessage("查询成功");
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("查询失败");
        }
        return responseBean;
    }

    @RequestMapping(value = "/findBatchByUserId", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/6/30
     * function: 根据学生userId批量获取实习信息 + 分页
     *
     * @param user
     * @return
     */
    public ResponseBean findBatchByUserId(@RequestBody User user) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //1. 先找到学生信息表
            StudentInfo studentInfo = studentInfoService.findOneByUserId(user.getId());
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo.getId());
            //设置分页参数
            internInfo.setPageIndex(user.getPageIndex());
            internInfo.setPageSize(user.getPageSize());
            if (internInfo.getPageIndex() > 0) // 若需要分页
                internInfo.setPageIndex(internInfo.getPageIndex() - 1);
            List<InternInfo> internInfos = internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails = new ArrayList<InternInfoDetail>();
            for (InternInfo internInfo1 : internInfos) {
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            responseBean.setData(internInfoDetails);
            responseBean.setTotal(internInfo.getTotal());
            responseBean.setSuccess(true);
            responseBean.setMessage("查询成功");
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

    @RequestMapping(value = "/findAll", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/7/3
     * function: 根据学生userId批量获取实习信息 + 分页
     *
     * @param user
     * @return
     */
    public ResponseBean findAll(@RequestBody InternInfo internInfo) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //设置分页参数
            if (internInfo.getPageIndex() > 0) // 若需要分页
                internInfo.setPageIndex(internInfo.getPageIndex() - 1);
            List<InternInfo> internInfos = internInfoService.findByCondition(internInfo);
            List<InternInfoDetail> internInfoDetails = new ArrayList<InternInfoDetail>();
            for (InternInfo internInfo1 : internInfos) {
                internInfoDetails.add(internInfoService.findDetailById(internInfo1.getId()));
            }
            responseBean.setData(internInfoDetails);
            responseBean.setTotal(internInfo.getTotal());
            responseBean.setSuccess(true);
            responseBean.setMessage("查询成功");
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("查询失败");
        }
        return responseBean;
    }

    /**
     * author: WheelChen
     * date: 2017/6/22
     * function: 根据id更新实习信息
     *
     * @param internInfo 实习信息
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean modify(@RequestBody InternInfo internInfo) {
        ResponseBean responseBean = new ResponseBean();
        try {
            processSuccessDeleteUpdate(internInfoService.modify(internInfo), responseBean);
            return responseBean;
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
            return responseBean;
        }
    }

    /**
     * author: WheelChen
     * date: 2017/6/22
     * function: 删除实习信息
     *
     * @param id 实习信息id
     * @return
     */
    @RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean remove(@PathVariable("id") Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            if (internInfoService.delete(id) > 0) {
                responseBean.setMessage("删除成功");
                responseBean.setSuccess(true);
            } else {
                responseBean.setMessage("删除失败");
                responseBean.setSuccess(false);
            }
            return responseBean;
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
            return responseBean;
        }
    }

    /**
     * author: WheelChen
     * date: 2017/6/22
     * function: 添加实习信息
     *
     * @param internInfo 实习信息
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean add(@RequestBody InternInfo internInfo) {
        ResponseBean responseBean = new ResponseBean();
        try {
            processSuccessDeleteUpdate(internInfoService.add(internInfo), responseBean);
            return responseBean;
        } catch (Exception e) {
            responseBean.setMessage("程序异常");
            responseBean.setSuccess(false);
            return responseBean;
        }
    }

    @RequestMapping(value = "/findOne/{id}", method = RequestMethod.GET)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/6/26
     * function: 根据实习信息表id查找实习信息
     *
     * @param id 实习信息表id
     * @return
     */
    public ResponseBean findOne(@PathVariable("id") Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            InternInfoDetail internInfoDetail = internInfoService.findDetailById(id);
            responseBean.setData(internInfoDetail);
            responseBean.setMessage("获取成功");
            responseBean.setSuccess(true);
            return responseBean;
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
            return responseBean;
        }
    }

    @RequestMapping(value = "/findBatchByCondition2", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/8/2
     * function: 根据学生表条件模糊查找每个学生最有效的一条信息（有现在实习信息优先显示……）
     *
     * @param internInfoDetail
     * @return
     */
    public ResponseBean findBatchByCondition2(@RequestBody StudentInfo studentInfo) {
        ResponseBean responseBean = new ResponseBean();
        if (studentInfo.getPageIndex() > 0) {
            studentInfo.setPageIndex(studentInfo.getPageIndex() - 1);
        }
//        //分页起始和大小
//        int pageIndex = internInfoDetail.getPageIndex() - 1;
//        int pageSize = internInfoDetail.getPageSize();
        List<InternInfoDetail> internInfoDetailList = new ArrayList<>();
        try {
            //根据学生信息表筛选出符合条件的学生信息表记录
            List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
            for (StudentInfo studentInfo1 : studentInfoList) {
                InternInfo internInfo = new InternInfo();
                internInfo.setSno(studentInfo1.getId());
                switch (studentInfo1.getState()) {
                    case STUDENTSTATE_NO: { //未实习 实习信息表一定为空 只需添加学生信息表信息
                        InternInfoDetail internInfoDetail1 = new InternInfoDetail();
                        StudentInfoDetail studentInfoDetail = studentInfoService.findDetailById(studentInfo1.getId());
                        internInfoDetail1.setStudentInfoDetail(studentInfoDetail);
                        internInfoDetailList.add(internInfoDetail1);
                        break;
                    }
                    case STUDENTSTATE_APPLY: { //实习申请中 说明实习信息表中一定只有一条记录处于审核流程中
                        internInfo = internInfoService.findOneBySnoAndReview(internInfo);
                        internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
                        break;
                    }
                    case STUDENTSTATE_ING: { //实习中显示正在实习的记录
                        internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
                        internInfo = internInfoService.findOneBySnoAndOragattr(internInfo); //查找正在实习的信息（仅有一条）
                        internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
                        break;
                    }
                    case STUDENTSTATE_CHANGE: { //实习变更中的显示实习中和实习
                        internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
                        internInfo = internInfoService.findOneBySnoAndOragattr(internInfo); //查找正在实习的信息（仅有一条）
                        InternInfoDetail internInfoDetail = internInfoService.findDetailById(internInfo.getId());

                        //查找审核中的实习信息也就是提交的变更的实习信息
                        InternInfo condition = new InternInfo();
                        condition.setSno(studentInfo1.getId());
                        condition = internInfoService.findOneBySnoAndReview(condition);
                        internInfoDetail.setChange(condition);
                        internInfoDetailList.add(internInfoDetail);

                    }
                }
//                        if (studentInfo1.getState() == STUDENTSTATE_ING || studentInfo1.getState() == STUDENTSTATE_CHANGE)
//                            internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
//                        internInfo = internInfoService.findOneBySnoAndOragattr(internInfo);
//                        if (internInfo != null)
//                            internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
//                        else {
//                            InternInfoDetail internInfoDetail1 = new InternInfoDetail();
//                            StudentInfoDetail studentInfoDetail = new StudentInfoDetail();
//                            studentInfoDetail.setStudentInfo(studentInfo);
//                            internInfoDetail1.setStudentInfoDetail(studentInfoDetail);
//                            internInfoDetailList.add(internInfoDetail1);
//                        }
            }
            responseBean.setTotal(studentInfo.getTotal());
            responseBean.setData(internInfoDetailList);
            responseBean.setSuccess(true);
            responseBean.setMessage("查询成功");
//                    //判断是否需要分页
//                    if (pageIndex > -1 && pageSize > 0 && (pageIndex + 1) * pageSize < studentInfoList.size()) {
//                        //
//                        for (int i = pageSize * pageIndex; i < pageSize * (pageIndex + 1); i++) {
//                            StudentInfo studentInfo1 = studentInfoList.get(i);
//                            InternInfo internInfo = new InternInfo();
//                            internInfo.setSno(studentInfo1.getId());
//                            if (studentInfo1.getState() == STUDENTSTATE_ING || studentInfo1.getState() == STUDENTSTATE_CHANGE)
//                                internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
//                            internInfo = internInfoService.findOneBySnoAndOragattr(internInfo);
//                            internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
//                        }
//                    } else {
//                        for (int i = pageIndex  * pageSize; i < studentInfoList.size(); i++) {
//                            StudentInfo studentInfo1 = studentInfoList.get(i);
//                            InternInfo internInfo = new InternInfo();
//                            internInfo.setSno(studentInfo1.getId());
//                            if (studentInfo1.getState() == STUDENTSTATE_ING || studentInfo1.getState() == STUDENTSTATE_CHANGE)
//                                internInfo.setOrgattr(Constants.ORGATTR.NOW.value());
//                            internInfo = internInfoService.findOneBySnoAndOragattr(internInfo);
//                            if (internInfo != null)
//                                internInfoDetailList.add(internInfoService.findDetailById(internInfo.getId()));
//                            else {
//                                InternInfoDetail internInfoDetail1 = new InternInfoDetail();
//                                StudentInfoDetail studentInfoDetail = new StudentInfoDetail();
//                                studentInfoDetail.setStudentInfo(studentInfo);
//                                internInfoDetail1.setStudentInfoDetail(studentInfoDetail);
//                                internInfoDetailList.add(internInfoDetail1);
//                            }
//                        }
//                    }
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

    @RequestMapping(value = "/findBatchByCondition3", method = RequestMethod.POST)
    @ResponseBody
    /**
     * author: WheelChen
     * date: 2017/8/2
     * function: 根据学生信息表、实习信息表条件模糊查找
     *
     * @param internInfoDetail
     * @return
     */
    public ResponseBean findBatchByCondition3(@RequestBody InternInfoDetail internInfoDetail) {
        ResponseBean responseBean = new ResponseBean();
        //分页起始和大小
        int pageIndex = internInfoDetail.getPageIndex() - 1;
        int pageSize = internInfoDetail.getPageSize();
        List<InternInfoDetail> internInfoDetailList = new ArrayList<>();
        try {
            if (internInfoDetail.getStudentInfoDetail() != null) {
                if (internInfoDetail.getStudentInfoDetail().getStudentInfo() != null) {
                    //首先根据学生信息表的条件进行筛选
                    StudentInfo studentInfo = internInfoDetail.getStudentInfoDetail().getStudentInfo();
                    //根据学生信息表筛选出符合条件的学生信息表记录
                    List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
                    List<Integer> snoList = new ArrayList<>();
                    for (StudentInfo studentInfo1 : studentInfoList){
                        snoList.add(studentInfo1.getId());
                    }
                    InternInfo internInfo = internInfoDetail.getInternInfo();
                    internInfo.setSnoList(snoList);
                    internInfo.setPageSize(pageSize);
                    internInfo.setPageIndex(pageIndex);
                    List<InternInfo> internInfoList = internInfoService.findByCondition(internInfo);
                    for (InternInfo internInfo1 : internInfoList) {
                        internInfoDetailList.add(internInfoService.findDetailById(internInfo1.getId()));
                    }
                    responseBean.setTotal(internInfo.getTotal());
                    responseBean.setData(internInfoDetailList);
                    responseBean.setSuccess(true);
                    responseBean.setMessage("查询成功");
                }
                else {
                    responseBean.setSuccess(false);
                    responseBean.setMessage("缺少学生表基本信息");
                }
            }
            else {
                responseBean.setSuccess(false);
                responseBean.setMessage("缺少学生详细信息");
            }
        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

    @RequestMapping(value = "/findIsUnderReview/{userId}", method = RequestMethod.GET)
    @ResponseBody
    /**
     * @api {get} /findIsUnderReview/:id 判断是否处于审核状态
     * @apiName findIsUnderReview
     * @apiGroup InternInfo
     *
     * @apiParam {Integer} userId 用户表id
     *
     * @apiSuccess {boolean} success 是否成功
     * @apiSuccess {int} flag 1 - 处于审核流程 2 - 不处于审核流程
     *
     * @apiSuccessExample Success-Response 处于审核流程:
     *     HTTP/1.1 200 OK
     *     {
     *       "success": true,
     *       "flag": "1",
     *       "message":"处于审核流程"
     *     }
     * @apiSuccessExample Success-Response 不处于审核流程:
     *     HTTP/1.1 200 OK
     *     {
     *       "success": true,
     *       "flag": "2"
     *       "message":"不处于审核流程"
     *     }
     *
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 404 程序异常
     *     {
     *       "success": false,
     *       "message":"程序异常"
     *     }
     */
    /**
     * author: WheelChen
     * date: 2017/8/3
     * function: 根据userId判断是否处于审核状态
     *
     * @param userId
     * @return
     */
    public ResponseBean findIsUnderReview(@PathVariable("userId") Integer userId){
        ResponseBean responseBean = new ResponseBean();
        try {
            StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);
            InternInfo internInfo = new InternInfo();
            internInfo.setSno(studentInfo.getId());
            if (internInfoService.checkIsUnderReview(internInfo)){
                responseBean.setSuccess(true);
                responseBean.setFlag(1);
                responseBean.setMessage("处于审核流程");
            }
            else {
                responseBean.setSuccess(true);
                responseBean.setFlag(2);
                responseBean.setMessage("不处于审核流程");
            }

        } catch (Exception e) {
            responseBean.setSuccess(false);
            responseBean.setMessage("程序异常");
        }
        return responseBean;
    }

}
